package com.photoeditor.demo.util.beauty;

import android.graphics.Bitmap;


public class WrapUtil {
    /**
     * @param src      原图像
     * @param col      控制参数
     * @param strength 增大强度，范围（0-1）
     * @return 处理后的图片
     * @desc 图像局部放大，可用于对眼睛的放大
     */
    public static Bitmap imageScale(Bitmap src, WarpControl col, double strength) {
        final int width = src.getWidth();
        final int height = src.getHeight();
        int[] src_pixels = new int[width * height];
        int[] res_pixels = new int[width * height];
        src.getPixels(src_pixels, 0, width, 0, 0, width, height);
        src.getPixels(res_pixels, 0, width, 0, 0, width, height);
        for (int y = (int) (col.orig_y - col.max_dist); y <= col.orig_y + col.max_dist; y++) {
            for (int x = (int) (col.orig_x - col.max_dist); x <= col.orig_x + col.max_dist; x++) {
                int inkx = edgeHandle(x, width);
                int inky = edgeHandle(y, height);
                int fu = inkx;
                int fv = inky;
                double dx = fu - col.orig_x;
                double dy = fv - col.orig_y;
                // dx>0-col.max_dist&&dx<col.max_dist&&dy>0-col.max_dist&&dy<col.max_dist
                if (hypotsq(dx, dy) < col.max_dist_sq) {
                    double rsq = hypotsq(dx, dy);
                    double rnorm = Math.sqrt(rsq / col.max_dist_sq);
                    double a = 1 - strength * (rnorm - 1) * (rnorm - 1);
                    fu = (int) (col.orig_x + a * dx);
                    fv = (int) (col.orig_y + a * dy);
                    fu = edgeHandle(fu, width);
                    fv = edgeHandle(fv, height);
                    res_pixels[inky * width + inkx] = src_pixels[fv * width + fu];
                }
            }
        }
        Bitmap resImg = Bitmap.createBitmap(res_pixels, width, height, Bitmap.Config.ARGB_8888);
//        Bitmap resImg = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
//        resImg.setPixels(res_pixels, 0, width, 0, 0, width, height);
        return resImg;
    }

    /**
     * 计算平方和
     * @param x
     * @param y
     * @return
     */
    public static double hypotsq(double x,double y){
        return x*x+y*y;
    }

    /**
     * 边缘处理防止越界
     * @param index
     * @param w
     * @return
     */
    public static int edgeHandle(int index, int w)
    {
        if(index<0)
            return 0;
        else
        if(index>=w)
            return w-1;
        else
            return index;
    }
}
